package bb.lanxing.calc.fixer;

import com.github.mikephil.charting.utils.Utils;
import bb.lanxing.calc.data.CadencePoint;
import bb.lanxing.calc.data.SourcePoint;
import bb.lanxing.util.Log;

public class AltitudeCorrector {
    final static private String TAG = "AltitudeCorrector";
    private SourcePoint lastSourcePoint;
    private boolean isPhoneAltitudeCalibrated = false;
    private double phoneAltitudeCalibratedOffset = Utils.DOUBLE_EPSILON;

    public void process(SourcePoint sourcePoint) {
        if (this.lastSourcePoint == null) {
            this.lastSourcePoint = sourcePoint;
            return;
        }
        Log.v(TAG, "AltitudeCorrector, hasPressure: " + sourcePoint.hasPressure());
        if (!sourcePoint.hasPressure()) {
            if (this.lastSourcePoint.hasPressure() && this.lastSourcePoint.getCadencePoint().isCalibrated()) {
                CadencePoint cadencePoint = this.lastSourcePoint.getCadencePoint();
                if (!this.isPhoneAltitudeCalibrated) {
                    this.phoneAltitudeCalibratedOffset = sourcePoint.getAltitude() - cadencePoint.getAltitude();
                    this.isPhoneAltitudeCalibrated = true;
                }
                double altitude = sourcePoint.getAltitude() - this.phoneAltitudeCalibratedOffset;
                sourcePoint.setAltitude(altitude);
                Log.v(TAG, "AltitudeCorrector, phone's altitude after corrected: " + altitude);
            }
        } else {
            this.isPhoneAltitudeCalibrated = false;
        }
        this.lastSourcePoint = sourcePoint;
    }

    public void release() {
        this.lastSourcePoint = null;
        this.isPhoneAltitudeCalibrated = false;
        this.phoneAltitudeCalibratedOffset = Utils.DOUBLE_EPSILON;
    }
}
